package Queuedemo;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 用队列实现栈
 */
class MyStack {
    public Queue<Integer> que1;
    public Queue<Integer> que2;

    public MyStack() {
        que1 = new LinkedList<>();
        que2 = new LinkedList<>();
    }

    //将元素存入栈中
    public void push(int x) {
        if(!que1.isEmpty()) {
            que1.offer(x);
        }else if(!que2.isEmpty()) {
            que2.offer(x);
        }else {
            que1.offer(x);
        }
    }

    //移除并返回栈顶元素
    public int pop() {
        if(!que1.isEmpty()) {
            int size = que1.size();
            while(size-1 != 0) {
                que2.offer(que1.poll());
                size--;
            }
            return que1.poll();
        }else if (!que2.isEmpty()) {
            int size = que2.size();
            while(size-1 != 0) {
                que1.offer(que2.poll());
                size--;
            }
            return que2.poll();
        }else {
            return -1;
        }
    }

    //返回栈顶元素
    public int top() {
        if(!que1.isEmpty()) {
            int size = que1.size();
            int tmp = -1;
            while(size != 0) {
                tmp = que1.peek();
                que2.offer(que1.poll());
                size--;
            }
            return tmp;
        }else if (!que2.isEmpty()) {
            int size = que2.size();
            int tmp = -1;
            while(size != 0) {
                tmp = que2.peek();
                que1.offer(que2.poll());
                size--;
            }
            return tmp;
        }else {
            return -1;
        }
    }

    //判断栈是否为空
    public boolean empty() {
        if(que1.isEmpty() && que2.isEmpty()) {
            return true;
        }
        return false;
    }
}